package com.simple.datax.db.service.impl;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.dubbo.common.logger.Logger;
import com.alibaba.dubbo.common.logger.LoggerFactory;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.simple.datax.SimpleMessage;
import com.simple.datax.SimpleResentMessage;
import com.simple.datax.db.mybatis.client.DataxProcingMapper;
import com.simple.datax.db.mybatis.model.DataxProcing;
import com.simple.datax.db.mybatis.model.DataxRecvRawMsg;
import com.simple.datax.db2.mybatis.client.DataxRecvRawMsgMapper;
import com.simple.datax.service.DBResentLoaderService;
import com.simple.datax.utils.SimpleConstants;

/**
 * @Title: DBResentLoaderServiceImpl.java
 * @Package com.simple.datax.db.service.impl
 * @Description: TODO(添加描述)
 * @author Paladin Chen
 * @date 2013-1-11 下午6:36:42
 * @version V1.0
 */
public class DBResentLoaderServiceImpl implements DBResentLoaderService {
	private static final Logger logger = LoggerFactory.getLogger(DBResentLoaderServiceImpl.class);
	@Autowired
	protected DataxRecvRawMsgMapper drrmm;

	@Autowired
	protected DataxProcingMapper dpm;

	@Override
	public List<SimpleResentMessage> getNeedResentProcing(int minutesBefore) {
		// DataxProcingCriteria example = new DataxProcingCriteria();
		// Date now = new Date();
		// example.createCriteria().andTimeLessThan(new
		// Date(now.getTime()-(minutesBefore*60*1000)));
		// List<DataxProcing> rett = dpm.selectByExample(example);

		List<DataxProcing> rett = dpm.selectByTimeBefore(minutesBefore);
		if (rett == null) {
			return null;
		}

		List<SimpleResentMessage> ret = new ArrayList<SimpleResentMessage>();

		for (DataxProcing dp : rett) {
			// 判断重发次数，到达最大次数直接删除，没有到达，增加重发次数; 该部分放到服务中处理
			/*
			 * if (maxRecount <= dp.getResendCount()) { try {
			 * dpm.deleteByPrimaryKey(dp.getRecvRawMsgid()); } catch (Exception
			 * e) { logger.info("Delete Procing Error:", e); } //记发送失败表
			 * MessageUtils.castFailMessage("重发次数超限。",
			 * SimpleConstants.ERROR_TYPE_RESEND,
			 * SimpleConstants.ERROR_LEVEL_CLASS, dp., msgType, recvRawMsgid,
			 * msgReceiver, msgSender, parseRawMsgid, sentRawMsgid) } else { try
			 * { dp.setResendCount((short)(dp.getResendCount() + 1));
			 * dpm.updateByPrimaryKey(dp); } catch (Exception e) {
			 * logger.info("Update Procing State Error:", e); }
			 * 
			 * ret.add(dp.getRecvRawMsgid()); }
			 */
			SimpleResentMessage srm = new SimpleResentMessage(dp.getRecvRawMsgid(), dp.getResendCount(), dp.getStatus());
			ret.add(srm);
		}

		return ret;
	}

	@Override
	@Transactional
	public void updateProcingCount(String imMsgid, short resendCount) {
		try {
			DataxProcing dp = new DataxProcing();

			dp.setRecvRawMsgid(imMsgid);
			dp.setResendCount(resendCount);
			// dp.setStatus(SimpleConstants.STATUS_RESENT);

			dpm.updateByPrimaryKeySelective(dp);
		} catch (Exception e) {
			logger.info("RecvRawMsgid(" + imMsgid + ") Update Procing resendcount Error:", e);
		}
	}

	@Override
	@Transactional
	public void deleteProcing(String id) {
		try {
			dpm.deleteByPrimaryKey(id);
		} catch (Exception e) {
			logger.info("RecvRawMsgid(" + id + ") Delete Procing Error:", e);
		}
	}

	@Override
	public SimpleMessage getResentMsgContent(String id, Short state) {
		try {
			DataxRecvRawMsg drrm = drrmm.selectByPrimaryKey(id);

			if (drrm != null) {
				SimpleMessage sm = new SimpleMessage();

				sm.setCommunParam(drrm.getCommunParam());
				sm.setCommunType(drrm.getCommunType());
				sm.setEncoding(drrm.getMsgCharset());
				sm.setRecvRawMsgid(drrm.getId());
				sm.setMsgFormat(drrm.getRecvDataType());
				sm.setMsgType(drrm.getMsgType());

				// 设置重发标志
				sm.setResendState(state);
				sm.setIntraMsg(checkIntraMsg(drrm.getCommunType()));
				sm.setContent(new String(drrm.getMsgData()));

				return sm;
			}
		} catch (Exception e) {
			logger.info("Find resent msg(" + id + ") Error:", e);
		}
		return null;
	}

	private boolean checkIntraMsg(String communType) {
		if (!StringUtils.isBlank(communType)) {
			if (communType.toUpperCase().indexOf(SimpleConstants.FLOW_COMMTYPE_POSTFIX) >= 0) {
				return true;
			}
		}

		return false;
	}

}
